import React, {Component} from 'react';
import ReactDOM from 'react-dom';

// import createContext from "./createContext";
interface PageProps {
}

interface PageState {
  color: string
}

interface ContextValue {
  color: string;
  changeColor: (color: string) => void
}

let ThemeContext = React.createContext<ContextValue | null>(null);
// let ThemeContext = createContext<ContextValue | null>(null);
let root: HTMLElement | null = document.querySelector('#root');

class Header extends Component {
  // Assign a contextType to read the current theme context.
  // React will find the closest theme Provider above and use its value.
  static contextType/*←必须叫这名*/ = ThemeContext;
  //一般类组件使用context使用这种形式(通过this.context.color取值)
  //函数组件则使用consumer的形式(通过<ThemeContext.Consumer>{value=> value.color取值) （但类也可以使用这种方式, 见下面 Main 就是）
  /** ↑ 之所以要这样指定, 是因为context可能有多个(你父亲有一个,你祖父又有一个), 这时就需要你指定你要使用哪个context*/

  render() {
    return (
      <div style={{border: `5px solid ${this.context.color}`, padding: 5}}>
        header
        <Title/>
      </div>
    )
  }
}
//↕ 等同于在外面这样写
//Header.contextType = ThemeContext

class Title extends Component {
  render() {
    return (
      <ThemeContext.Consumer>
        {
          (value: ContextValue | null) => (
            <div style={{border: `5px solid ${value!.color}`}}>
              title
            </div>
          )
        }
      </ThemeContext.Consumer>
    )
  }
}

class Main extends Component {
  render() {
    return (
      <ThemeContext.Consumer>
        {
          (value: ContextValue | null) => (
            <div style={{border: `5px solid ${value!.color}`, margin: 5, padding: 5}}>
              main
              <Content/>
            </div>
          )
        }
      </ThemeContext.Consumer>
    )
  }
}

class Content extends Component {
  render() {
    return (
      <ThemeContext.Consumer>
        {
          (value: ContextValue | null) => (
            <div style={{border: `5px solid ${value!.color}`, padding: 5}}>
              Content
              <button onClick={() => value!.changeColor('red')} style={{color: 'red'}}>红色</button>
              <button onClick={() => value!.changeColor('green')} style={{color: 'green'}}>绿色
              </button>
            </div>
          )
        }
      </ThemeContext.Consumer>

    )
  }
}

class Page extends Component<PageProps, PageState> {
  constructor(props: PageProps) {
    super(props);
    this.state = {color: 'red'};
  }

  changeColor = (color: string) => {
    this.setState({color});
  };

  render() {
    let contextVal: ContextValue = {changeColor: this.changeColor, color: this.state.color};
    return (
      <ThemeContext.Provider value={contextVal}>
        <div
          style={{margin: '10px', border: `5px solid ${this.state.color}`, padding: 5, width: 200}}>
          page
          <Header/>
          <Main/>
        </div>
      </ThemeContext.Provider>
    )
  }
}

ReactDOM.render(<Page/>, root);
